<?php

function baidu_api($url) {
    $ch = curl_init();

    $header = array(
                'apikey:37a3919aad4704950d45602281beae11',
                'Accept-Charset:UTF-8'
            );

    curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 执行HTTP请求
    curl_setopt($ch , CURLOPT_URL , $url);
    $res = curl_exec($ch);

    $info = curl_getinfo($ch);

    curl_close($ch);

    if ($info['http_code'] >= 200 && $info['http_code'] <= 299)
        return json_decode($res, true);

    return FALSE;
}

/*
 * $json = json_decode('{"a": 111, "b": 222}');
 * foreach ($json as $key => $val) {
 *     echo getType($key), PHP_EOL;
 *     echo getType($val), PHP_EOL;
 * }
 *
 * exit(0);
 */


function weather($name)
{
    //天气查询
    $url = 'http://apis.baidu.com/apistore/weatherservice/';

    $city = urlencode($name);
    // $city = urlencode("深圳");
    // $cityid = '101280601';
    // $name_en = 'shenzhen';
    //查询可用城市信息
    // $url .= 'citylist?cityname='.$city;

    //查询历史7天和未来4天和当天的天气情况
    // $url .= 'recentweathers?cityname='.$city.'&cityid='.$cityid;

    //根据城市名称查询天气
    $url .= "cityname?cityname=".$city;

    $data = "";
    $json = baidu_api($url);
    foreach ($json as $key => $val) {
        $data .= "$key = ";
        if (is_array($val)) {
            $data .= "<br />";
            foreach ($val as $k => $v) {
                $data .= "&emsp;&emsp;$k = $v<br />";
            }
        } else {
            $data .= $val;
        }
        $data .= "<br />";
    }

    return $data;
}

$get = "";
foreach ($_GET as $key => $val) {
    $get .= "$key=$val&";
}
$get = rtrim($get, "&");

if (isset($_GET['name']))
    $data = weather($_GET['name']);
else
    $data = "错误信息: 请正确输入城市名称!";

echo "请求方法: ", $_SERVER["REQUEST_METHOD"], "<br />";
echo "请求URL: ", $get, "<br />";
echo "==== 以下为服务器回应的数据 ====</br />";
echo $data;

